// 调试API调用的工具
import { communityApi } from "@/api/community";
import { API_ENDPOINTS } from "@/config/api";

export const debugCommunityApi = async () => {
  console.log("🔍 开始调试社区API...");
  console.log("📋 API端点配置:", API_ENDPOINTS.COMMUNITY.SHARES);

  // 首先检查token状态
  const hasToken = checkTokenStatus();
  if (!hasToken) {
    console.error("❌ 没有token，无法继续测试");
    return;
  }

  try {
    console.log("📡 调用 communityApi.getShares...");
    const response = await communityApi.getShares({
      page: 1,
    });
    console.log("✅ API响应:", response);
    return response;
  } catch (error) {
    console.error("❌ API错误:", error);
    if (error instanceof Error) {
      console.error("错误消息:", error.message);
    }
    if (error && typeof error === "object" && "response" in error) {
      const axiosError = error as any;
      console.error("HTTP状态:", axiosError.response?.status);
      console.error("响应数据:", axiosError.response?.data);
      console.error("请求URL:", axiosError.config?.url);
      console.error("请求参数:", axiosError.config?.params);
      console.error("请求头:", axiosError.config?.headers);
      console.error("完整请求配置:", axiosError.config);
    }
    throw error;
  }
};

// 检查是否有其他地方在调用这个接口
export const checkApiCalls = () => {
  console.log("🔍 检查API调用...");

  // 检查是否有其他地方在调用相同的接口
  const originalFetch = window.fetch;
  window.fetch = function (...args) {
    const url = args[0];
    if (typeof url === "string" && url.includes("community/shares")) {
      console.log("🚨 发现fetch调用:", url, args);
      console.trace("调用堆栈:");
    }
    return originalFetch.apply(this, args);
  };

  console.log("✅ 已设置fetch监听器");
};

// 测试简单的API调用
export const testSimpleApi = async () => {
  console.log("🧪 测试简单API调用...");

  const token = localStorage.getItem("token");
  if (!token) {
    console.error("❌ 没有token");
    return;
  }

  try {
    const response = await fetch("/api/v1/community/shares?page=1", {
      method: "GET",
      headers: {
        Authorization: `Bearer ${token}`,
        "Content-Type": "application/json",
        Accept: "application/json",
      },
    });

    console.log("📡 响应状态:", response.status);
    console.log("📡 响应头:", Object.fromEntries(response.headers.entries()));

    if (response.ok) {
      const data = await response.json();
      console.log("✅ 响应数据:", data);
    } else {
      const errorText = await response.text();
      console.error("❌ 错误响应:", errorText);
    }
  } catch (error) {
    console.error("❌ 请求失败:", error);
  }
};

// 检查token状态
export const checkTokenStatus = () => {
  console.log("🔍 检查Token状态...");

  const token = localStorage.getItem("token");
  const user = localStorage.getItem("user");

  console.log(
    "🎫 Token:",
    token ? `存在 (${token.substring(0, 20)}...)` : "不存在"
  );
  console.log("👤 User:", user ? JSON.parse(user) : "不存在");

  if (!token) {
    console.warn("⚠️ 没有找到token，请先登录");
    return false;
  }

  return true;
};

// 在浏览器控制台中可以调用这些函数
if (typeof window !== "undefined") {
  (window as any).debugCommunityApi = debugCommunityApi;
  (window as any).checkApiCalls = checkApiCalls;
  (window as any).checkTokenStatus = checkTokenStatus;
  (window as any).testSimpleApi = testSimpleApi;
}
// 测试数据库连接
export const testDatabase = async () => {
  console.log("🗄️ 测试数据库连接...");

  const token = localStorage.getItem("token");
  if (!token) {
    console.error("❌ 没有token");
    return;
  }

  try {
    const response = await fetch("/api/v1/test/database", {
      method: "GET",
      headers: {
        Authorization: `Bearer ${token}`,
        "Content-Type": "application/json",
        Accept: "application/json",
      },
    });

    console.log("📡 数据库测试响应状态:", response.status);

    if (response.ok) {
      const data = await response.json();
      console.log("✅ 数据库连接正常:", data);
    } else {
      const errorText = await response.text();
      console.error("❌ 数据库连接失败:", errorText);
    }
  } catch (error) {
    console.error("❌ 数据库测试请求失败:", error);
  }
};

// 测试无需认证的API
export const testPublicApi = async () => {
  console.log("🌐 测试公开API...");

  try {
    const response = await fetch("/api/v1/test/ping", {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
    });

    console.log("📡 公开API响应状态:", response.status);

    if (response.ok) {
      const data = await response.json();
      console.log("✅ 公开API正常:", data);
    } else {
      const errorText = await response.text();
      console.error("❌ 公开API失败:", errorText);
    }
  } catch (error) {
    console.error("❌ 公开API请求失败:", error);
  }
};

// 运行完整的诊断测试
export const runFullDiagnostic = async () => {
  console.log("🔬 开始完整诊断测试...");
  console.log("=".repeat(50));

  // 1. 检查token状态
  console.log("1️⃣ 检查认证状态");
  const hasToken = checkTokenStatus();

  if (!hasToken) {
    console.error("❌ 诊断终止：没有有效的token");
    return;
  }

  console.log("=".repeat(50));

  // 2. 测试公开API
  console.log("2️⃣ 测试基础API连接");
  await testPublicApi();

  console.log("=".repeat(50));

  // 3. 测试数据库连接
  console.log("3️⃣ 测试数据库连接");
  await testDatabase();

  console.log("=".repeat(50));

  // 4. 测试社区API（直接调用）
  console.log("4️⃣ 测试社区API（直接调用）");
  await testSimpleApi();

  console.log("=".repeat(50));

  // 5. 测试社区API（通过封装方法）
  console.log("5️⃣ 测试社区API（通过封装方法）");
  try {
    await debugCommunityApi();
  } catch (error) {
    console.error("封装方法测试失败");
  }

  console.log("=".repeat(50));
  console.log("🏁 诊断测试完成");
};

// 更新全局函数
if (typeof window !== "undefined") {
  (window as any).testDatabase = testDatabase;
  (window as any).testPublicApi = testPublicApi;
  (window as any).runFullDiagnostic = runFullDiagnostic;
}
